<template>
  <div>
    <!-- 导航面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" size="mini">添加角色</el-button>
        </el-col>
      </el-row>

      <el-table :data="roles" border stripe>
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-row :gutter="20" v-for="(item1, l1) in props.row.children" :key="item1.id" :class="['vcenter', 'border-bottom', l1 === 0 ? 'border-top' : '']">
              <el-col :span="5">
                <el-tag closable @close="removeRightById(props.row, item1.id)">
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row v-for="(item2, i2) in item1.children" :key="item2.id" :class="i2 === item1.children.length - 1 ? '' : 'border-bottom'">
                  <el-col :span="6">
                    <el-tag closable type="success" @close="removeRightById(props.row, item2.id)">
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag v-for="item3 in item2.children" :key="item3.id" type="warning" closable @close="removeRightById(props.row, item3.id)">
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" prop="desc">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限视图 -->
    <el-dialog title="分配权限" :visible.sync="dialogSetRightVisible" @close="setRightDialogClosed">
      <el-tree :data="allRight" ref="treeRef" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" :props="defaultProps"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogSetRightVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getRoles, deleteRoleRight, getRightsTree, authorization } from "@/api/rights";
export default {
  data() {
    return {
      roles: [],
      dialogSetRightVisible: false,
      allRight: [],
      defaultProps: {
        label: "authName",
        children: "children"
      },
      defKeys: [],
      // 当前即将分配权限的角色id
      roleId: ""
    };
  },
  created() {
    this.requestRoles();
  },
  components: {},

  methods: {
    removeRightById(role, rightId) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteRoleRight(role.id, rightId).then(res => {
            if (res.meta.status !== 200) return this.$message.error("删除角色中的权限有误");
            this.$message.success("删除成功");
            role.children = res.data;
            // this.requestRoles()
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    requestRoles() {
      getRoles().then(res => {
        console.log(res);
        if (res.meta.status !== 200) return this.$message.error("获取角色错误");
        this.roles = res.data;
      });
    },
    showSetRightDialog(role) {
      this.roleId = role.id;
      getRightsTree().then(res => {
        if (res.meta.status !== 200) return this.$message.error("获取权限列表树失败");
        this.allRight = res.data;
        this.getLeafKeys(role);
        this.dialogSetRightVisible = true;
      });
    },
    // 通过递归的形式，获取角色下所有三级权限的id，并保存到 defKeys 数组中
    getLeafKeys(right) {
      if (right.children === undefined) {
        return this.defKeys.push(right.id);
      }
      right.children.forEach(item => {
        this.getLeafKeys(item);
      });
    },
    setRightDialogClosed() {
      this.defKeys = [];
    },
    //分配权限
    allotRights() {
      // authorization
      //   const keys = this.$refs.treeRef.getCheckedKeys().concat(this.$refs.treeRef.getHalfCheckedKeys());
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()];
      authorization(this.roleId, keys.join(",")).then(res => {
        if (res.meta.status !== 200) return this.$message.error("分配权限失败");
        this.$message.success("分配权限成功！");
        this.requestRoles();
        this.dialogSetRightVisible = false;
      });
    }
  }
};
</script>

<style scoped>
.el-tag {
  margin: 7px;
}
.vcenter {
  display: flex;
  align-items: center;
}
.border-bottom {
  border-bottom: 1px solid #eee;
}
.border-top {
  border-top: 1px solid #eee;
}
</style>
